package com.qxzn.module.agora;

import android.content.Context;
import android.view.SurfaceView;
import android.view.View;

import java.util.HashMap;

import io.agora.rtc.Constants;
import io.agora.rtc.IRtcEngineEventHandler;
import io.agora.rtc.RtcEngine;
import io.agora.rtc.video.VideoCanvas;

/**
 * Created by Administrator on 2019/1/10.
 */

public class AgoraManager {

    public static int mLocalUid = 0;//当前用户ID
    private static AgoraManager mAgoraManager;
    private RtcEngine mRtcEngine;//引擎
    private HashMap<Integer, SurfaceView> mUserIdMap;//用户集合
    //此集合仅用于用于桌面版机器人项目，记录当前用户在第一排还是第二排
    //key:uid，value:1/2 1表示第一排，2表示第二排
    private HashMap<Integer, Integer> mUserCurrentRow;
    private OnUserStatusChangeListener mUserStatusChangeListener;
    private IRtcEngineEventHandler mRtcEngineEventHandler = new IRtcEngineEventHandler() {
        @Override
        public void onJoinChannelSuccess(String channel, int uid, int elapsed) {
            if (mUserStatusChangeListener != null) {
                mUserStatusChangeListener.onJoinChannelSuccess(channel, uid, elapsed);
            }
        }

        @Override
        public void onFirstRemoteVideoDecoded(int uid, int width, int height, int elapsed) {
            if (mUserStatusChangeListener != null) {
                mUserStatusChangeListener.onFirstRemoteVideoDecoded(uid, width, height, elapsed);
            }
        }

        @Override
        public void onUserJoined(int uid, int elapsed) {
            if (mUserStatusChangeListener != null) {
                mUserStatusChangeListener.onUserJoined(uid, elapsed);
            }
        }

        @Override
        public void onUserOffline(int uid, int reason) {
            if (mUserStatusChangeListener != null) {
                mUserStatusChangeListener.onUserOffline(uid, reason);
            }
        }
    };

    private AgoraManager() {
        mUserIdMap = new HashMap<>();
        mUserCurrentRow = new HashMap<>();
    }

    public static AgoraManager getInstance() {
        if (mAgoraManager == null) {
            synchronized (AgoraManager.class) {
                if (mAgoraManager == null) {
                    mAgoraManager = new AgoraManager();
                }
            }
        }
        return mAgoraManager;
    }

    public void setOnUserStatusChangeListener(OnUserStatusChangeListener listener) {
        this.mUserStatusChangeListener = listener;
    }

    /**
     * 初始化RtcEngine
     */
    public void init(Context context) {
        if (mRtcEngine != null) {
            return;
        }
        //创建RtcEngine对象，mRtcEventHandler为RtcEngine的回调
        try {
            mRtcEngine = RtcEngine.create(context, context.getString(R.string.agora_id), mRtcEngineEventHandler);
            //开启视频功能
            mRtcEngine.enableVideo();
            //视频配置，设置为360P
            mRtcEngine.setVideoProfile(Constants.VIDEO_PROFILE_720P, false);
            mRtcEngine.setChannelProfile(Constants.CHANNEL_PROFILE_COMMUNICATION);//设置为通信模式（默认）
//        mRtcEngine.setChannelProfile(Constants.CHANNEL_PROFILE_LIVE_BROADCASTING);设置为直播模式
//        mRtcEngine.setChannelProfile(Constants.CHANNEL_PROFILE_GAME);设置为游戏模式

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置本地视频，即前置摄像头预览
     */
    public AgoraManager setupLocalVideo(Context context) {
        //创建一个SurfaceView用作视频预览
        SurfaceView surfaceView = RtcEngine.CreateRendererView(context);
        //将SurfaceView保存起来在SparseArray中，后续会将其加入界面。key为视频的用户id，这里是本地视频, 默认id是0
        surfaceView.setTag(mLocalUid);
        //surfaceView.setZOrderMediaOverlay(true);
        mUserIdMap.put(mLocalUid, surfaceView);
        surfaceView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mUserStatusChangeListener != null) {
                    mUserStatusChangeListener.onSurfaceItemClick(mLocalUid);
                }
            }
        });
        //设置本地视频，渲染模式选择VideoCanvas.RENDER_MODE_HIDDEN，如果选其他模式会出现视频不会填充满整个SurfaceView的情况，
        //具体渲染模式参考官方文档https://docs.agora.io/cn/user_guide/API/android_api.html#set-local-video-view-setuplocalvideo
        mRtcEngine.setupLocalVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_HIDDEN, mLocalUid));
        return this;//返回AgoraManager以作链式调用
    }

    public AgoraManager setupRemoteVideo(Context context, final int uid) {
        SurfaceView surfaceView = RtcEngine.CreateRendererView(context);
        surfaceView.setTag(uid);
        mUserIdMap.put(uid, surfaceView);
        //surfaceView.setZOrderMediaOverlay(true);
        surfaceView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mUserStatusChangeListener != null) {
                    mUserStatusChangeListener.onSurfaceItemClick(uid);
                }
            }
        });
        mRtcEngine.setupRemoteVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_HIDDEN, uid));
        return this;
    }

    public AgoraManager joinChannel(String channel) {
        mRtcEngine.joinChannel(null, channel, null, 0);
        return this;
    }

    public void startPreview() {
        mRtcEngine.startPreview();
    }

    public void stopPreview() {
        if (mRtcEngine != null) {
            mRtcEngine.stopPreview();
        }
    }

    public void stopSendLocalAudio(boolean flag) {
        mRtcEngine.muteLocalAudioStream(flag);
    }

    public void stopReciveAllRemoteAudio(boolean flag) {
        mRtcEngine.muteAllRemoteAudioStreams(flag);
    }

    public void destroy() {
        RtcEngine.destroy();
        mRtcEngine = null;
    }

    public void leaveChannel() {
        if (mRtcEngine != null) {
            mRtcEngine.leaveChannel();
        }
    }

    public void silence(boolean flag) {
        mRtcEngine.muteLocalAudioStream(flag);
    }

    /**
     * 切换摄像头
     */
    public void switchCamera() {
        if (mRtcEngine != null) {
            mRtcEngine.switchCamera();
        }
    }

    public void removeSurfaceView(int uid) {
        mUserIdMap.remove(uid);
    }

    public SurfaceView getLocalSurfaceView() {
        return mUserIdMap.get(mLocalUid);
    }

    public SurfaceView getSurfaceView(int uid) {
        return mUserIdMap.get(uid);
    }

    public HashMap<Integer, SurfaceView> getUserMap() {
        return mUserIdMap;
    }

    public HashMap<Integer, Integer> getUserCurrentRow() {
        return mUserCurrentRow;
    }

    public interface OnUserStatusChangeListener {
        void onJoinChannelSuccess(String channel, int uid, int elapsed);

        void onFirstRemoteVideoDecoded(int uid, int width, int height, int elapsed);

        void onUserJoined(int uid, int elapsed);

        void onUserOffline(int uid, int reason);

        void onSurfaceItemClick(int uid);
    }
}
